package com.atguigu.day06;

import com.atguigu.utils.UserBehavior;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.sql.Timestamp;
import java.time.Duration;
import java.util.HashSet;

// 计算每个1小时里的独立访客统计指标（uv，unique vistors）
public class Example8 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment
                .getExecutionEnvironment();
        env.setParallelism(1);

        SingleOutputStreamOperator<UserBehavior> stream = env
                .readTextFile("/home/zuoyuan/flink0609/src/main/resources/UserBehavior.csv")
                .map(new MapFunction<String, UserBehavior>() {
                    @Override
                    public UserBehavior map(String value) throws Exception {
                        String[] array = value.split(",");
                        return new UserBehavior(
                                array[0],
                                array[1],
                                array[2],
                                array[3],
                                Long.parseLong(array[4]) * 1000L
                        );
                    }
                })
                // 将pv数据过滤出来
                .filter(r -> r.type.equals("pv"))
                // 插入水位线
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<UserBehavior>forBoundedOutOfOrderness(Duration.ofSeconds(0))
                                .withTimestampAssigner(new SerializableTimestampAssigner<UserBehavior>() {
                                    @Override
                                    public long extractTimestamp(UserBehavior element, long recordTimestamp) {
                                        return element.ts;
                                    }
                                })
                );

        stream
                // 按照userId分流
                .keyBy(r -> r.userId)
                // 开窗口
                // 每个窗口里userId都是一样的，所以只能算作1个uv
                .window(TumblingEventTimeWindows.of(Time.hours(1)))
                // 增量聚合函数和全窗口聚合函数结合使用
                .aggregate(new CountAgg(), new WindowResult())
                // 按照窗口进行逻辑分区
                // 每个逻辑分区都是某个窗口的不同userId的1
                // 所以将每个窗口的1累加起来就可以了
                .keyBy(r -> r.f0)
                .process(new KeyedProcessFunction<Long, Tuple2<Long, Long>, String>() {
                    // 累加器
                    private ValueState<Long> uv;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        super.open(parameters);
                        uv = getRuntimeContext().getState(
                                new ValueStateDescriptor<Long>(
                                        "uv",
                                        Types.LONG
                                )
                        );
                    }

                    @Override
                    public void processElement(Tuple2<Long, Long> value, Context ctx, Collector<String> out) throws Exception {
                        // 每来一个1,就加到累加器上
                        if (uv.value() == null) uv.update(1L);
                        else uv.update(uv.value() + 1L);

                        // 注册定时器
                        ctx
                                .timerService()
                                .registerEventTimeTimer(
                                        value.f0 + 1L
                                );
                    }

                    @Override
                    public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
                        super.onTimer(timestamp, ctx, out);
                        // 输出计算结果就可以了
                        out.collect(
                                "窗口结束时间：" + new Timestamp(timestamp - 1L) + "" +
                                        "的窗口里的uv是：" + uv.value()
                        );
                    }
                })
                .print();

        env.execute();
    }

    public static class CountAgg implements AggregateFunction<UserBehavior, Long, Long> {
        @Override
        public Long createAccumulator() {
            return 0L;
        }

        // 由于窗口里的uv只能算1次，所以累加器永远是1
        @Override
        public Long add(UserBehavior value, Long accumulator) {
            return 1L;
        }

        // 把1输出到全窗口聚合函数
        @Override
        public Long getResult(Long accumulator) {
            return accumulator;
        }

        @Override
        public Long merge(Long a, Long b) {
            return null;
        }
    }

    public static class WindowResult extends ProcessWindowFunction<
            Long, Tuple2<Long, Long>, String, TimeWindow> {
        // 把1包装一层窗口信息
        @Override
        public void process(String s, Context context, Iterable<Long> elements, Collector<Tuple2<Long, Long>> out) throws Exception {
            out.collect(
                    Tuple2.of(
                            context.window().getEnd(), // 窗口结束时间
                            1L                         // 窗口中的uv是1
                    )
            );
        }
    }
}
